package web.suzy.oj.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import web.suzy.oj.dao.user.SysUserRoleEntityService;
import web.suzy.oj.dao.user.UserInfoEntityService;
import web.suzy.oj.mapper.SysRoleAuthMapper;
import web.suzy.oj.pojo.entity.user.SysAuth;
import web.suzy.oj.pojo.entity.user.SysRole;
import web.suzy.oj.pojo.entity.user.UserInfo;
import web.suzy.oj.utils.JwtUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * YangSuzy 软件工作室
 * 类名: AccountRealm
 * 描述: 自定义账户Realm
 * 功能: ---- 待定 -----
 *
 * @author YangSuzy
 * Date: 2022/11/14 15:25
 */
@Slf4j
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private SysUserRoleEntityService userRoleEntityService;

    @Autowired
    private UserInfoEntityService userInfoEntityService;

    @Autowired
    private SysRoleAuthMapper roleAuthMapper;

    /**
     * 方法名: supports
     * 描述: 存在多个Realm时标记此 Realm专门用来验证 JwtToken
     *
     * @param token
     * @return boolean
     * @date 2022/11/14 16:03
     * @auther YangSuzy
     **/
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 方法名: doGetAuthorizationInfo
     * 描述: 用户授权，获取授权信息
     *
     * @param principals
     * @return org.apache.shiro.authz.AuthorizationInfo
     * @date 2022/11/14 16:04
     * @auther YangSuzy
     **/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        AccountProfile user = (AccountProfile) principals.getPrimaryPrincipal();
        //角色权限列表
        List<String> permissionsNameList = new LinkedList<>();
        //用户角色列表
        List<String> roleNameList = new LinkedList<>();
        //获取该用户角色所有的权限
        List<SysRole> roles = userRoleEntityService.getRolesByUid(user.getUid());
        for (SysRole role : roles) {
            roleNameList.add(role.getRole());
            for (SysAuth auth : roleAuthMapper.getRoleAuths(role.getId()).getAuths()) {
                permissionsNameList.add(auth.getPermission());
            }
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //添加角色
        authorizationInfo.addRoles(roleNameList);
        //添加权限
        authorizationInfo.addStringPermissions(permissionsNameList);
        return authorizationInfo;
    }


    /**
     * 方法名: doGetAuthenticationInfo
     * 描述: 用户认证，获取身份信息
     *
     * @param token
     * @return org.apache.shiro.authc.AuthenticationInfo
     * @date 2022/11/14 16:07
     * @auther YangSuzy
     **/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //此Realm专门认证JwtToken
        JwtToken jwt = (JwtToken) token;
        //从token中获取用户ID
        String userId = jwtUtils.getClaimByToken((String) jwt.getPrincipal()).getSubject();
        //根据用户ID查询用户信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", userId)
                .select("uuid", "username", "nickname", "realname", "avatar", "status");
        UserInfo userInfo = userInfoEntityService.getOne(queryWrapper, false);
        //判断用户状态
        if (userInfo == null) {
            throw new UnknownAccountException("账户不存在！");
        }
        if (userInfo.getStatus() == 1) {
            throw new LockedAccountException("该账户已被封禁，请联系管理员进行处理！");
        }
        //保存用户认证信息
        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(userInfo, profile);
        profile.setUid(userInfo.getUuid());
        return new SimpleAuthenticationInfo(profile, jwt.getCredentials(), getName());
    }
}
